package com.egg.common.util;


import com.egg.common.core.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件 工具类
 *
 * @author east
 */
@Slf4j
public class FileUtil {


    public static MultipartFile convertToMultipart(File file) {
        try {
            InputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
            return multipartFile;
        } catch (Exception e) {
            log.error("转换文件失败 ", e);
            throw new CustomException("转换文件失败");
        }
    }

    public static File convertToFile(MultipartFile multipartFile) {
        try {
            File file = new File(multipartFile.getOriginalFilename());
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(multipartFile.getBytes());
            outputStream.close();
            return file;
        } catch (Exception e) {
            log.error("转换文件失败 ", e);
            throw new CustomException("转换文件失败");
        }
    }


    private static String zhPattern = "[\\u4e00-\\u9fa5]";

    /**
     * 替换字符串卷
     *
     * @param str     被替换的字符串
     * @param charset 字符集
     * @return 替换好的
     * @throws UnsupportedEncodingException 不支持的字符集
     */
    private static String encode(String str, String charset) throws UnsupportedEncodingException {
        String changeUrl = str.replace(" ", "%20");
        Pattern p = Pattern.compile(zhPattern);
        Matcher m = p.matcher(changeUrl);
        StringBuffer b = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
        }
        m.appendTail(b);
        return b.toString();
    }

    /**
     * 链接转MP4文件
     *
     * @param urlString
     * @return
     * @throws IOException
     */
    private static File urlToMp4File(String urlString) throws IOException {
        URL url = new URL(encode(urlString, "UTF-8"));
        URLConnection connection = url.openConnection();
        InputStream input = connection.getInputStream(); // 打开输入流
        // 创建一个临时文件
        File tempFile = File.createTempFile("video-", ".mp4");
        FileOutputStream output = new FileOutputStream(tempFile); // 打开输出流
        // 读取数据并写入到本地文件中
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }
        // 关闭输入和输出流
        input.close();
        output.close();
        return tempFile;
    }

    /**
     * 计算视频时长
     *
     * @param url
     * @return
     */
    public static long getVideoDuration(String url) {
        File file = null;
        try {
            file = urlToMp4File(url);
            MultimediaObject instance = new MultimediaObject(file);
            MultimediaInfo result = instance.getInfo();
            long seconds = result.getDuration() / 1000;
            return seconds;
        } catch (Exception e) {
            log.error("计算视频时长失败 ", e);
        } finally {
            if (null != file) {
                file.deleteOnExit();
            }
        }
        return 0;
    }

    public static byte[] convertFileToBytes(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            InputStream inputStream = url.openStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        } catch (IOException e) {
            log.error("转换文件 {} 失败 {}", fileUrl, e.getMessage());
        }
        return null;
    }

}